package com.pandi.springboot_jwt.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

public class EncryptUtil {
    private static final Logger logger = LoggerFactory.getLogger(EncryptUtil.class);

    private static final byte[] DESIV = new byte[] { 0x12, 0x34, 0x56, 120, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef };// 向量

    private static AlgorithmParameterSpec iv = null;// 加密算法的参数接口
    private static Key key = null;

    private static String charset = "utf-8";

    static{
        try{
            String salt = "x-a~t*l$";
            DESKeySpec keySpec = new DESKeySpec(salt.getBytes(EncryptUtil.charset));// 设置密钥参数
            iv = new IvParameterSpec(DESIV);// 设置向量
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
            key = keyFactory.generateSecret(keySpec);// 得到密钥对象
        }catch (Exception e){
            logger.error("Failed to initialize EncryptUtil! The error is {}", e.getMessage());
        }
    }

    /**
     * 加密
     */
    public static String encode(String data) {
        try{
            Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
            enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式，给出密钥和向量
            byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
            BASE64Encoder base64Encoder = new BASE64Encoder();
            return base64Encoder.encode(pasByte);
        }catch (Exception e){
            logger.error("Failed to encode in EncryptUtil! The error is {}", e.getMessage());
            return null;
        }
    }

    /**
     * 解密
     */
    public static String decode(String data) {
        try{
            Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            deCipher.init(Cipher.DECRYPT_MODE, key, iv);
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));
            return new String(pasByte, "UTF-8");
        }catch (Exception e){
            logger.error("Failed to decode in EncryptUtil! The error is {}", e.getMessage());
            return null;
        }
    }

    public static void main(String[] args) {
        try {
            String test = "HB908803";
            System.out.println("加密前的字符：" + test);
            String encodStr = EncryptUtil.encode(test);
            System.out.println("加密后的字符：" + encodStr);
            String decodeStr = EncryptUtil.decode("FC7IwF1Oc80XY3xsdiWqkQ==");
            System.out.println("解密后的字符：" + decodeStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
